<template>
  <div class="equip-wrap-common equip-index-status">
    <div class="index-status-header">
      <div class="status-status">
        设备运行状态：
        <px-tag
          v-if="props.equipmentTitle.equipmentStatusDesc"
          effect="plain"
          :style="{
            color: `${props.equipmentTitle.equipmentStatus === '5' ? '#000' : '#fff'}`,
            border: 'none',
            backgroundColor: `${tagBgColorList[props.equipmentTitle.equipmentStatus]}`
          }"
        >
          {{ props.equipmentTitle.equipmentStatusDesc }}
        </px-tag>
        <span v-else>-</span>
      </div>
      <div class="status-time">
        最近一次上报时间：<span>{{ props.equipmentTitle.lastReportTime ? props.equipmentTitle.lastReportTime : "-" }}</span>
      </div>
      <px-button class="status-refresh" type="primary" plain @click="refreshPage">刷新</px-button>
    </div>
    <px-table :data="props.tableData" class="equip-table" height="calc(100vh - 358px)" border>
      <px-table-column type="index" label="序号" width="60" />
      <px-table-column label="点位编码" prop="positionNum" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.positionNum || "-" }}
        </template>
      </px-table-column>
      <px-table-column label="点位描述" prop="attributeName" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.attributeName || "-" }}
        </template>
      </px-table-column>
      <px-table-column label="数据类型" prop="valueType" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.valueType || "-" }}
        </template>
      </px-table-column>
      <px-table-column label="当前值" align="center" min-width="180" prop="attributeValue">
        <template #default="scope">
          <px-tooltip v-if="scope.row.isClick == true" content="点击查看属性趋势" placement="top">
            <span style="color: #3b82f6; cursor: pointer" @click="showTendency(scope.row)">{{ scope.row.attributeValue || "-" }}</span>
          </px-tooltip>
          <span v-else>{{ scope.row.attributeValue || "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="单位" align="center" min-width="120" prop="valueUnitDesc">
        <template #default="scope">
          {{ scope.row.valueUnitDesc || "-" }}
        </template>
      </px-table-column>
      <px-table-column label="是否在可视化展示" min-width="140" align="center" prop="showOnVisualization">
        <template #default="scope">
          <px-switch
            v-model="scope.row.isShowVisual"
            v-has="ALL_EQUIP_ARCHIVE_LIST_VISUAL"
            :disabled="scope.row.showOnVisualization === 2"
            @change="handleSwitch(scope.row)"
          />
        </template>
      </px-table-column>
      <px-table-column label="最新更新时间" min-width="160" align="center" prop="lastReportTime">
        <template #default="scope">
          {{ scope.row.lastReportTime || "-" }}
        </template>
      </px-table-column>
    </px-table>
    <px-dialog v-model="tendencyVisible" align-center title="属性趋势" style="width: 1080px">
      <px-radio-group v-model="time" @change="settime">
        <px-radio-button label="1小时" />
        <px-radio-button label="6小时" />
        <px-radio-button label="12小时" />
        <px-radio-button label="1天" />
        <px-radio-button label="自定义" />
      </px-radio-group>
      <px-date-picker
        v-if="time == '自定义'"
        v-model="times"
        style="position: absolute; right: 30px"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD hh:mm:ss"
        unlink-panels
        :disabled-date="disabledTime"
        @change="checkTime"
      />
      <chartdiv style="margin-top: 20px" :width="'1000px'" :height="'560px'" :option="option" />
    </px-dialog>
  </div>
</template>

<script setup>
import { getPositionNumGraph, closeVisualTag, openVisualTag } from "@/api/equip/archive";
import { ref } from "vue";
import chartdiv from "./echartsDom.vue";

const tagBgColorList = {
  1: "#10B981", // 运行
  2: "#9254DE", // 故障（报警且停机）/异常停机
  3: "#F59E0B", // 带病（报警且运行）/异常
  4: "#909399", // 离线
  5: "#efefef" // 停机
};
const emits = defineEmits(["queryTable", "queryPage"]);
const props = defineProps(["tableData", "equipmentTitle"]);
const positionNum = ref(null);
const tendencyVisible = ref(false);
const option = ref({});
const valueUnitDesc = ref("");
const attributeName = ref("");
// 刷新页面调用父级查询表格
const refreshPage = () => {
  emits("queryPage");
};
// 禁用时间
const disabledTime = time => {
  const disabledBefore = time.getTime() < Date.now() - 8.64e7 - 365 * 24 * 60 * 60 * 1000; // 禁用早于1年前时间
  const disabledAfter = time.getTime() > Date.now() - 8.64e7; // 禁用晚于今天时间
  return disabledBefore || disabledAfter;
};
const checkTime = () => {
  getTendency(times.value[0], times.value[1]);
};
const settime = val => {
  if (val == "1小时") {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 1);
    times.value = [formatDate(start), formatDate(end)];
    getTendency(times.value[0], times.value[1]);
  }
  if (val == "6小时") {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 6);
    times.value = [formatDate(start), formatDate(end)];
    getTendency(times.value[0], times.value[1]);
  }
  if (val == "12小时") {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 12);
    times.value = [formatDate(start), formatDate(end)];
    getTendency(times.value[0], times.value[1]);
  }
  if (val == "1天") {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24);
    times.value = [formatDate(start), formatDate(end)];
    getTendency(times.value[0], times.value[1]);
  }
  if (val == "自定义") {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 365 * 3600 * 1000 * 24);
    times.value = [formatDate(start), formatDate(end)];
    getTendency(times.value[0], times.value[1]);
  }
};
const time = ref("1天");
const times = ref("");

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
// 展示趋势图
const showTendency = row => {
  positionNum.value = row.positionNum;
  valueUnitDesc.value = row.valueUnitDesc;
  attributeName.value = row.attributeName;
  tendencyVisible.value = true;
  time.value = "1天";
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24);
  times.value = [formatDate(start), formatDate(end)];
  getTendency(times.value[0], times.value[1]);
};

// 更新是否在可视化展示这个状态
const handleSwitch = async row => {
  const { positionNum, showOnVisualization } = row;
  if (showOnVisualization === 0) {
    const res = await openVisualTag({ positionNum });
    emits("queryTable");
  } else if (showOnVisualization === 1) {
    const res = await closeVisualTag({ positionNum });
    emits("queryTable");
  }
};

// 趋势图展示方法
const getTendency = async (startTime, endTime) => {
  const data = await getPositionNumGraph({ startTime: startTime, endTime: endTime, positionNum: positionNum.value });
  option.value = {
    legend: {
      bottom: 0
    },
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    grid: {
      left: "20px",
      top: "40px",
      right: "60px",
      bottom: "30px",
      containLabel: true
    },
    xAxis: [
      {
        type: "category",
        name: "时间",
        data: data.dateList
      }
    ],
    yAxis: [
      {
        type: "value",
        name: valueUnitDesc.value
      }
    ],
    series: [
      {
        name: attributeName.value,
        type: "line",
        data: data.positionValList
      }
    ]
  };
};
</script>
<style scoped lang="scss">
.equip-index-status {
  .index-status-header {
    display: flex;
    align-items: center;
    height: 32px;
    margin-top: 8px;
    margin-bottom: 16px;

    .status-status {
      display: flex;
      align-items: center;
    }

    .status-time {
      margin-right: 24px;
      margin-left: 16px;
    }
  }

  .equip-table {
    --px-table-border-color: #dfdfdf;

    :deep(.px-table__header) {
      thead {
        tr {
          background-color: #e7eefb !important;

          th {
            font-size: 13px;
            font-weight: bold;
            color: #000;
            background-color: #e7eefb !important;
          }
        }
      }
    }
  }
}
</style>
